package com.yowasa.xiuxian.config;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.yowasa.xiuxian.interceptor.TokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * HTTP请求客户端配置类
 */
@Configuration
public class RestTemplateConfig {

    @Autowired
    TokenInterceptor tokenInterceptor;

    @Bean
    public RestTemplate restTemplate() {
        //HTTP请求拦截器
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(tokenInterceptor);
        //报文信息转换器
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder = new Jackson2ObjectMapperBuilder();
        jackson2ObjectMapperBuilder.serializationInclusion(JsonInclude.Include.NON_NULL);
        jackson2ObjectMapperBuilder.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        jackson2ObjectMapperBuilder.failOnUnknownProperties(false);
        ObjectMapper mapper = jackson2ObjectMapperBuilder.build();
        messageConverter.setObjectMapper(mapper);
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new MappingJackson2HttpMessageConverter(mapper));
        messageConverters.add(new FormHttpMessageConverter());
        RestTemplate restTemplate = new RestTemplate(messageConverters);
        //RestTemplate对象
        restTemplate.setInterceptors(interceptors);
        return restTemplate;
    }
}
